﻿using System.Collections.Generic;
using Framework;

namespace Game
{
    public class SceneObjectStateComposite : Composite<SceneObjectBTContext>
    {
        private List<SceneObjectStateTransition> _transitionList = new List<SceneObjectStateTransition>();

        public override void OnStart(SceneObjectBTContext context)
        {
            base.OnStart(context);
            _transitionList.Sort(CompareTransition);
        }

        public override TaskStatus Update(SceneObjectBTContext context)
        {
            for (int i = 0; i < _transitionList.Count; ++i)
            {
                SceneObjectStateTransition transition = _transitionList[i];
                if ((transition.fromState == -1 || transition.fromState == _currentChildIndex)
                    && transition.CanTransfer(context))
                {
                    ChangeState(transition.toState, context);
                    break;
                }
            }
            Behavior<SceneObjectBTContext> child = _children[_currentChildIndex];
            status = child.Tick(context);
            return status;
        }

        public void AddTransition(SceneObjectStateTransition transition)
        {
            _transitionList.Add(transition);
        }

        private void ChangeState(int state, SceneObjectBTContext context)
        {
            if (_currentChildIndex == state)
            {
                return;
            }
            Behavior<SceneObjectBTContext> child = _children[_currentChildIndex];
            if (child.status == TaskStatus.Running)
            {
                child.status = TaskStatus.Invalid;
                child.OnEnd(context);
            }
            _currentChildIndex = state;
        }
        
        private int CompareTransition(SceneObjectStateTransition transition1, SceneObjectStateTransition transition2)
        {
            if (transition1.priority < transition2.priority)
            {
                return 1;
            }
            return -1;
        }
    }
}